<template>
  <div class="box">
    <video
      id="videoCamera"
      class="video"
      autoplay
      :width="videoWidth"
      :height="videoHeight"
    ></video>
    <canvas
      style="display: none"
      id="canvasCamera"
      :width="videoWidth"
      :height="videoHeight"
    ></canvas>
    <div v-if="imgSrc" class="img_bg_camera">
      <p class="text">效果预览</p>
      <img :src="imgSrc" alt class="tx_img" />
    </div>
    <div class="time">识别结果(耗时{{ time }}ms):</div>
    <div class="right-box" id="curve_show"></div>
    <div class="button">
      <!-- <el-button @click="getCompetence()" type="success" size="mini" plain >打开摄像头</el-button> -->
      <el-button @click="setImage()" type="success" size="small" plain
        >拍照识别</el-button
      >
      <!-- <el-button @click="stopNavigator()" type="success" size="mini" plain>关闭摄像头</el-button> -->
    </div>
    <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
    <div class="bottom">
      <router-view v-if="this.imgSrc != ''"></router-view>
    </div>
  </div>
</template>
<script>
import * as echarts from "echarts";
import { photoOrVdieo } from "@/api/index";
//引入
import { path } from "@/utils/host";
export default {
  data() {
    return {
      videoWidth: 280,
      videoHeight: 330,
      imgSrc: "",
      thisCancas: null,
      thisContext: null,
      thisVideo: null,
      openVideo: false,
      disease: ["苹果黑星病", "葡萄黑腐病", "番茄叶斑病"],
      probability: [9, 20, 10],
      myChart: {},
      time: 0,
      startTime: 0,
      endTime: 0,
      path,
      ws: null,
    };
  },
  mounted() {
    var myChart = echarts.init(document.getElementById("curve_show"));
    this.myChart = myChart;

    this.$router.push("/shibie/paizhao/appleDesease"); //打开病害详情

    this.init(); //初始化WebSocket
    this.getCompetence(); //进入页面就调用摄像头
    this.initCurve(); //初始化统计图

    setInterval(() => {
      if (!this.status) {
        this.ws.close(); //关闭WebSocket
        this.stopNavigator();
        clearInterval();
      }
    }, 1000);
  },
  computed: {
    status() {
      //  计算属性，打开识别页以及打开摄像头则为true，否则为false
      return this.$store.state.vdieoStatus && this.$store.state.menuBar; //  Vuex 中定义的属性
    },
  },
  methods: {
    //init函数可在页面加载的时候就进行初始化或者根据自己的业务需求在需要打开通讯的时候在进行初始化
    init() {
      if (typeof WebSocket == "undefined") {
        console.log("您的浏览器不支持WebSocket");
      } else {
        console.log("您的浏览器支持WebSocket");
        if (this.ws != null) {
          this.ws.close();
          this.ws = null;
        }
        // 实例化socket，这里的实例化直接赋值给this.ws是为了后面可以在其它的函数中也能调用websocket方法，例如：this.ws.close(); 完成通信后关闭WebSocket连接
        this.ws = new WebSocket(this.path + Math.round(Math.random() * 100));

        //监听是否连接成功
        this.ws.onopen = () => {
          console.log("ws连接状态：" + this.ws.readyState);
          //连接成功则发送一个数据
          // this.ws.send("连接成功");
        };

        //接听服务器发回的信息并处理展示
        this.ws.onmessage = (msg) => {
          //获得得到后端响应时的时间
          this.endTime = new Date().getTime();
          //耗时
          this.time = this.endTime - this.startTime;
          // console.log("接收到来自服务器的消息：");
          // console.log(msg);
          let data = JSON.parse(msg.data);
          // console.log(data);
          if (data.disease) {
            //不为空
            this.disease = data.disease;
            this.probability = data.probability;
            this.$store.commit("setDisease", this.disease[0]); //存储病害名称，用于搜索病害详情
            this.initCurve(); //更新统计图
          }
        };

        //监听连接关闭事件
        this.ws.onclose = () => {
          //监听整个过程中websocket的状态
          console.log("ws连接状态：" + this.ws.readyState);
        };

        //监听并处理error事件
        this.ws.onerror = function (error) {
          console.log(error);
        };
      }
    },
    // 调用权限（打开摄像头功能）
    getCompetence() {
      var _this = this;
      _this.thisCancas = document.getElementById("canvasCamera");
      _this.thisContext = this.thisCancas.getContext("2d");
      _this.thisVideo = document.getElementById("videoCamera");
      _this.thisVideo.style.display = "block";
      // 获取媒体属性，旧版本浏览器可能不支持mediaDevices，我们首先设置一个空对象
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {};
      }
      // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
      // 使用getUserMedia，因为它会覆盖现有的属性。
      // 这里，如果缺少getUserMedia属性，就添加它。
      if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function (constraints) {
          // 首先获取现存的getUserMedia(如果存在)
          var getUserMedia =
            navigator.webkitGetUserMedia ||
            navigator.mozGetUserMedia ||
            navigator.getUserMedia;
          // 有些浏览器不支持，会返回错误信息
          // 保持接口一致
          if (!getUserMedia) {
            //不存在则报错
            return Promise.reject(
              new Error("getUserMedia is not implemented in this browser")
            );
          }
          // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
          return new Promise(function (resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject);
          });
        };
      }
      var constraints = {
        audio: false,
        video: {
          width: this.videoWidth,
          height: this.videoHeight,
          transform: "scaleX(-1)",
        },
      };
      navigator.mediaDevices
        .getUserMedia(constraints)
        .then(function (stream) {
          // 旧的浏览器可能没有srcObject
          if ("srcObject" in _this.thisVideo) {
            _this.thisVideo.srcObject = stream;
          } else {
            // 避免在新的浏览器中使用它，因为它正在被弃用。
            _this.thisVideo.src = window.URL.createObjectURL(stream);
          }
          _this.thisVideo.onloadedmetadata = function (e) {
            _this.thisVideo.play();
          };
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //  绘制图片（拍照功能）
    async setImage() {
      var _this = this;
      // canvas画图
      _this.thisContext.drawImage(
        _this.thisVideo,
        0,
        0,
        _this.videoWidth,
        _this.videoHeight
      );
      // 获取图片base64链接
      var image = this.thisCancas.toDataURL("image/jpg");
      _this.imgSrc = image; //赋值并预览图片
      //删除编码前的标记
      let imgData = JSON.stringify({
        imgData: image.replace(/^data:image\/(png|jpg);base64,/, ""),
      });
      // console.log(imgData);
      // console.log(typeof imgData);
      //获得发送请求之前开始时间
      this.startTime = new Date().getTime();
      //请求后端，发送消息
      this.ws.send(imgData);

      // console.log("imgData==="+imgData);
      // let startTime = new Date().getTime();
      // await photoOrVdieo(imgData).then((res) => {
      //   let endTime = new Date().getTime();
      //   this.time = endTime - startTime;
      //   // console.log("res=================" + JSON.stringify(res.data));
      //   this.disease = JSON.parse(JSON.stringify(res.data)).data.disease;
      //   this.probability = JSON.parse(JSON.stringify(res.data)).data.probability;
      //   this.$store.commit("setDisease", this.disease[0]);
      // });

      // this.initCurve();
    },
    // 关闭摄像头
    stopNavigator() {
      this.thisVideo.srcObject.getTracks()[0].stop();
      // alert("关闭摄像头");
    },
    initCurve() {
      // var myChart = echarts.init(document.getElementById("curve_show"));
      this.myChart.setOption({
        title: {
          text: "Top3 病害预测结果",
          left: "center",
        },
        //鼠标悬停显示
        tooltip: {
          trigger: "item",
          formatter: "置信度：<br/>{b}: {c}%",
        },
        xAxis: {
          type: "category",
          name: "病害",
          data: this.disease,
        },
        color: ["#54924b", "#54924b", "#54924b"],
        yAxis: {
          type: "value",
          name: "置信度",
        },
        series: [
          {
            data: this.probability,
            type: "bar",
            barWidth: "50%",
            showBackground: true,
            backgroundStyle: {
              color: "rgba(180, 180, 180, 0.2)",
            },
            itemStyle: {
              normal: {
                label: {
                  show: true, //开启显示
                  position: "top", //在上方显示
                  formatter: "{c}%",
                  textStyle: {
                    //数值样式
                    color: "black",
                    fontSize: 12,
                  },
                },
              },
            },
          },
        ],
      });
    },
  },
};
</script>
<style scoped>
.box {
  width: 1100px;
  height: 420px;
  background-color: rgb(255, 255, 255);
  margin: auto;
  position: relative;
}
.video {
  /* width:400px;
    height:400px; */
  float: left;
  margin-left: 40px;
  /* position: relative; */
  margin-top: -2px;
}
.button {
  position: absolute;
  margin-top: 330px;
  margin-left: 140px;
}
.text {
  position: absolute;
  left: 40px;
}
.img_bg_camera {
  width: 350px;
  height: 400px;
  float: left;
  position: relative;
  margin-left: 40px;
  margin-top: -2px;
}

.right-box {
  width: 396px;
  height: 390px;
  background-color: rgb(255, 255, 255);
  float: right;
  margin-top: 0px;
  margin-left: -20px;
}
.bottom {
  margin-left: 10px;
  margin-top: -100px;
}
.time {
  margin-left: 730px;
  font-size: 20px;
}
</style>
